package com.christina.config;

import com.christina.engine.factory.ServiceExecutorFactory;
import com.christina.engine.factory.impl.DefaultServiceExecutorFactory;
import com.christina.engine.observer.EventManager;
import com.christina.engine.observer.impl.AuditLogListener;
import com.christina.engine.observer.impl.MetricsCollectionListener;
import com.christina.engine.parameter.builder.ParameterBuilderFactory;
import com.christina.engine.processing.RequestProcessorChain;
import com.christina.engine.processing.impl.*;
import com.christina.engine.response.decorator.ResponseDecorator;
import com.christina.engine.response.decorator.impl.CachingResponseDecorator;
import com.christina.engine.response.decorator.impl.FormattingResponseDecorator;
import com.christina.engine.response.decorator.impl.LoggingResponseDecorator;
import com.christina.engine.singleton.ConfigurationManager;
import com.christina.engine.state.ConversationStateManager;
import com.christina.engine.state.impl.CompletedState;
import com.christina.engine.state.impl.InformationGatheringState;
import com.christina.engine.state.impl.InitialState;
import com.christina.engine.state.impl.ProcessingState;
import com.christina.engine.strategy.RoutingStrategyManager;
import com.christina.engine.strategy.impl.ContextAwareRoutingStrategy;
import com.christina.engine.strategy.impl.IntentBasedRoutingStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import jakarta.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * 设计模式集成配置
 * 负责将所有设计模式组件整合到系统中
 * 
 * @author Christina
 */
@Slf4j
@Configuration
public class DesignPatternIntegrationConfig {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    /**
     * 配置管理器单例
     */
    @Bean
    public ConfigurationManager configurationManager() {
        return ConfigurationManager.getInstance();
    }
    
    /**
     * 事件管理器
     */
    @Bean
    public EventManager eventManager() {
        return new EventManager();
    }
    
    /**
     * 指标收集监听器
     */
    @Bean
    public MetricsCollectionListener metricsCollectionListener() {
        return new MetricsCollectionListener();
    }
    
    /**
     * 审计日志监听器
     */
    @Bean
    public AuditLogListener auditLogListener() {
        return new AuditLogListener();
    }
    
    /**
     * 路由策略管理器
     */
    @Bean
    public RoutingStrategyManager routingStrategyManager() {
        return new RoutingStrategyManager();
    }
    
    /**
     * 基于意图的路由策略
     */
    @Bean
    public IntentBasedRoutingStrategy intentBasedRoutingStrategy() {
        return new IntentBasedRoutingStrategy();
    }
    
    /**
     * 上下文感知路由策略
     */
    @Bean
    public ContextAwareRoutingStrategy contextAwareRoutingStrategy() {
        return new ContextAwareRoutingStrategy();
    }
    
    /**
     * 服务执行器工厂
     */
    @Bean
    public ServiceExecutorFactory serviceExecutorFactory() {
        return new DefaultServiceExecutorFactory(applicationContext);
    }
    
    /**
     * 参数建造者工厂
     */
    @Bean
    public ParameterBuilderFactory parameterBuilderFactory() {
        return new ParameterBuilderFactory(applicationContext);
    }
    
    /**
     * 对话状态管理器
     */
    @Bean
    public ConversationStateManager conversationStateManager() {
        return new ConversationStateManager();
    }
    
    /**
     * 初始状态
     */
    @Bean
    public InitialState initialState() {
        return new InitialState();
    }
    
    /**
     * 处理状态
     */
    @Bean
    public ProcessingState processingState() {
        return new ProcessingState();
    }
    
    /**
     * 信息收集状态
     */
    @Bean
    public InformationGatheringState informationGatheringState() {
        return new InformationGatheringState();
    }
    
    /**
     * 完成状态
     */
    @Bean
    public CompletedState completedState() {
        return new CompletedState();
    }
    
    /**
     * 日志装饰器
     */
    @Bean
    public LoggingResponseDecorator loggingResponseDecorator() {
        return new LoggingResponseDecorator();
    }
    
    /**
     * 缓存装饰器
     */
    @Bean
    public CachingResponseDecorator cachingResponseDecorator() {
        return new CachingResponseDecorator();
    }
    
    /**
     * 格式化装饰器
     */
    @Bean
    public FormattingResponseDecorator formattingResponseDecorator() {
        return new FormattingResponseDecorator();
    }
    
    /**
     * 响应装饰器链
     */
    @Bean
    public List<ResponseDecorator> responseDecoratorChain(
            LoggingResponseDecorator loggingDecorator,
            CachingResponseDecorator cachingDecorator,
            FormattingResponseDecorator formattingDecorator) {
        return Arrays.asList(loggingDecorator, cachingDecorator, formattingDecorator);
    }
    
    /**
     * 请求处理器链
     */
    @Bean
    @DependsOn({"eventManager", "routingStrategyManager", "serviceExecutorFactory"})
    public RequestProcessorChain requestProcessorChain(
            ValidationProcessor validationProcessor,
            ContextProcessor contextProcessor,
            IntentProcessor intentProcessor,
            DecisionProcessor decisionProcessor,
            RoutingProcessor routingProcessor,
            ExecutionProcessor executionProcessor,
            ResponseProcessor responseProcessor) {
        
        RequestProcessorChain chain = new RequestProcessorChain();
        
        // 按顺序注册处理器
        chain.registerProcessor(validationProcessor);
        chain.registerProcessor(contextProcessor);
        chain.registerProcessor(intentProcessor);
        chain.registerProcessor(decisionProcessor);
        chain.registerProcessor(routingProcessor);
        chain.registerProcessor(executionProcessor);
        chain.registerProcessor(responseProcessor);
        
        return chain;
    }
    
    /**
     * 初始化所有设计模式组件
     */
    @PostConstruct
    public void initializeDesignPatterns() {
        log.info("开始初始化设计模式组件...");
        
        try {
            // 初始化事件系统
            initializeEventSystem();
            
            // 初始化路由策略
            initializeRoutingStrategies();
            
            // 初始化状态管理
            initializeStateManagement();
            
            // 初始化配置管理
            initializeConfigurationManagement();
            
            log.info("设计模式组件初始化完成！");
            
        } catch (Exception e) {
            log.error("设计模式组件初始化失败", e);
            throw new RuntimeException("Failed to initialize design pattern components", e);
        }
    }
    
    /**
     * 初始化事件系统
     */
    private void initializeEventSystem() {
        EventManager eventManager = applicationContext.getBean(EventManager.class);
        MetricsCollectionListener metricsListener = applicationContext.getBean(MetricsCollectionListener.class);
        AuditLogListener auditListener = applicationContext.getBean(AuditLogListener.class);
        
        // 注册事件监听器
        eventManager.registerListener(metricsListener);
        eventManager.registerListener(auditListener);
        
        log.info("事件系统初始化完成 - 注册了 {} 个监听器", 
                eventManager.getAllListeners().size());
    }
    
    /**
     * 初始化路由策略
     */
    private void initializeRoutingStrategies() {
        RoutingStrategyManager strategyManager = applicationContext.getBean(RoutingStrategyManager.class);
        IntentBasedRoutingStrategy intentStrategy = applicationContext.getBean(IntentBasedRoutingStrategy.class);
        ContextAwareRoutingStrategy contextStrategy = applicationContext.getBean(ContextAwareRoutingStrategy.class);
        
        // 注册路由策略
        strategyManager.registerStrategy(intentStrategy);
        strategyManager.registerStrategy(contextStrategy);
        
        log.info("路由策略初始化完成 - 注册了 {} 个策略", 
                strategyManager.getStrategyCount());
    }
    
    /**
     * 初始化状态管理
     */
    private void initializeStateManagement() {
        ConversationStateManager stateManager = applicationContext.getBean(ConversationStateManager.class);
        InitialState initialState = applicationContext.getBean(InitialState.class);
        ProcessingState processingState = applicationContext.getBean(ProcessingState.class);
        InformationGatheringState gatheringState = applicationContext.getBean(InformationGatheringState.class);
        CompletedState completedState = applicationContext.getBean(CompletedState.class);
        
        // 注册对话状态
        stateManager.registerState(initialState);
        stateManager.registerState(processingState);
        stateManager.registerState(gatheringState);
        stateManager.registerState(completedState);
        
        log.info("状态管理初始化完成 - 注册了 {} 个状态", 
                stateManager.getStatistics().get("registeredStates"));
    }
    
    /**
     * 初始化配置管理
     */
    private void initializeConfigurationManagement() {
        ConfigurationManager configManager = ConfigurationManager.getInstance();
        
        // 添加配置变更监听器
        configManager.addConfigurationChangeListener(event -> {
            log.info("配置变更: {} = {} (版本: {})", 
                    event.getKey(), event.getNewValue(), event.getVersion());
        });
        
        // 设置设计模式相关配置
        configManager.setConfiguration("design-patterns.enabled", true, "启用设计模式", true);
        configManager.setConfiguration("design-patterns.version", "1.0.0", "设计模式版本", true);
        
        log.info("配置管理初始化完成 - 当前版本: {}", configManager.getConfigVersion());
    }
}